package excel.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.usian.common.exception.CatchConsumerException;
import com.usian.model.common.dtos.ResponseResult;
import excel.mapper.TestMapper;
import excel.mapper.UserMapper;
import excel.pojo.Test;
import excel.pojo.User;
import excel.service.UserService;
import excel.util.ExportUtils;
import excel.util.ImportUtils;
import excel.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 秉性哥
 * @createTime 2022/10/27 13:20
 * @description
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TestMapper testMapper;

    //导入 需要的常量
    private static final String PATH_FILE="D:\\";

    private static final String IMPORT_FILE_NAME="导入.xlsx";

    //导出 需要的常量

    private static final String[] HANDERS={"序号","用户名","密码","结束时间","失败次数"};

    private static final String[] HANDERS_POJO={"id","username","password","exportExcel","fail_count"};

    private static final int [] HANDERS_SIZE={10, 20, 10, 30,20};

    private static final String EXPORT_FILEZIP_NAME = "D:\\导出zip.zip" ;

    @Override
    public void add(Test test){
        test.setName("xx");
        for (int i = 0; i < 1000000; i++) {
            testMapper.insert(test);
        }
        System.out.println("----------------------------添加成功");
    }

    /**
     *@description 分页查询
     *@author  秉性哥
     *@params  Integer pageIndex, Map serachMap
     *@return  PageInfo
     *@createTime  2022/10/29
     */
    @Override
    public PageInfo findPage(Integer pageIndex, Map serachMap) {

        PageHelper.startPage(pageIndex,2);
        List<User> list= userMapper.findPage(serachMap);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo ;
    }

    /**
     *@description
     *@author  秉性哥
     *@params  Integer id
     *@return  ResponseResult
     *@createTime  2022/10/29
     */
    @Override
    public ResponseResult del(Integer id) {
        removeById(id);
        return new ResponseResult().ok("删除成功");
    }

    /**
     *@description 添加
     *@author  秉性哥
     *@params  User user
     *@return  ResponseResult
     *@createTime  2022/10/29
     */
    @Override
    public ResponseResult add(User user) {
        user.setFail_count(0);
        user.setEnd_login_date(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        save(user);
      return new ResponseResult().ok("添加成功");
    }
    /**
     *@description
     *@author  秉性哥
     *@params
     *@return
     *@createTime  2022/10/29
     */
    @Override
    public ResponseResult edit(User user){
        user.setFail_count(0);
        user.setEnd_login_date(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        updateById(user);
        return new ResponseResult().ok("修改成功");
    }



    /**
     *@description
     *@author  秉性哥
     *@params  Integer id
     *@return  ResponseResult
     *@createTime  2022/10/29
     */
    @Override
    public ResponseResult findById(Integer id) {
        User user = getById(id);
        return new ResponseResult().ok(user);
    }


    /**
     *@description 导入方法
     *@author  秉性哥
     *@params
     *@return ResponseResult
     *@createTime  2022/10/29
     */
    @Override
    public ResponseResult poiImport() {
        //用来存放Excel表格中的User对象
        ArrayList<User> userList = new ArrayList<>();
        ImportUtils.importExcel(IMPORT_FILE_NAME,PATH_FILE,userList);
        if (userList.size()==0 || userList==null){
            CatchConsumerException.catchException(20003,"Excel表格没有内容");
        }
        saveBatch(userList);
        return new ResponseResult().ok("导入成功");
    }


    /**
     *@description 导出方法
     *@author  秉性哥
     *@params
     *@return ResponseResult
     *@createTime  2022/10/29
     */
    @Override
    public ResponseResult poiExport(HttpServletResponse response) {
        List<User> list = list();
        //导出xsl格式（拆分多个sheet）
        PageUtils.exportExcel(response, "分页导出", HANDERS_POJO, HANDERS,  HANDERS_SIZE,list);
        return new ResponseResult().ok("导出成功");
    }


    /**
     *@description 导出方法
     *@author  秉性哥
     *@params
     *@return ResponseResult
     *@createTime  2022/10/29
     */
    @Override
    public ResponseResult poiExportZip(HttpServletResponse response,Integer pageIndex, Map serachMap) throws IOException {
        PageHelper.startPage(pageIndex,2);
        List<User> userList= userMapper.findPage(serachMap);
        PageInfo pageInfo = new PageInfo(userList);
        List<User> listAll = list();
        List<User> list1 = listAll.subList(0,2);
        List<User> list2 = listAll.subList(2,4);
        List<User> list3 = listAll.subList(4,6);
        ExportUtils.exportExcelZip(response,(int)Math.ceil(pageInfo.getTotal()*1.0 /2),HANDERS,list1,list2,list3,EXPORT_FILEZIP_NAME);
        return new ResponseResult().ok("导出成功");
    }

    @Override
    public ResponseResult poiExportCsv(HttpServletResponse response){
        List<User>list=list();
        ExportUtils.exportCSVFile(response,list,HANDERS);
        return new ResponseResult().ok("导出成功");
    }

   /* @Override
    public ResponseResult export(User user, HttpServletResponse response) {
        // 总记录数
        Integer totalRowCount = userMapper.selectUserCount();

        // 导出EXCEL文件名称
        String filaName = "用户EXCEL";

        // 标题
        String[] titles = {"账号", "密码", "状态", "昵称", "职位", "手机号", "邮箱", "创建人ID", "创建时间", "修改人ID", "修改时间"};

        // 开始导入
        PoiUtils.exportExcelToWebsite(response, totalRowCount, filaName, titles, new WriteExcelDataDelegated() {
            @Override
            public void writeExcelData(SXSSFSheet eachSheet, Integer startRowCount, Integer endRowCount, Integer currentPage, Integer pageSize) throws Exception {

                PageHelper.startPage(currentPage, pageSize);
                List<User> userVOList = userMapper.selectUserVOList(userVO);

                if (!CollectionUtils.isEmpty(userVOList)) {

                    // --------------   这一块变量照着抄就行  强迫症 后期也封装起来     ----------------------
                    for (int i = startRowCount; i <= endRowCount; i++) {
                        SXSSFRow eachDataRow = eachSheet.createRow(i);
                        if ((i - startRowCount) < userVOList.size()) {

                            User eachUserVO = userVOList.get(i - startRowCount);
                            // ---------   这一块变量照着抄就行  强迫症 后期也封装起来     -----------------------

                            eachDataRow.createCell(0).setCellValue(eachUserVO.getUsername() == null ? "" : eachUserVO.getUsername());
                            eachDataRow.createCell(1).setCellValue(eachUserVO.getPassword() == null ? "" : eachUserVO.getPassword());
                            eachDataRow.createCell(2).setCellValue(eachUserVO.getUserState() == null ? "" : (eachUserVO.getUserState() == 1 ? "启用" : "停用"));
                            eachDataRow.createCell(3).setCellValue(eachUserVO.getNickname() == null ? "" : eachUserVO.getNickname());
                            eachDataRow.createCell(4).setCellValue(eachUserVO.getPosition() == null ? "" : eachUserVO.getPosition());
                            eachDataRow.createCell(5).setCellValue(eachUserVO.getMobile() == null ? "" : eachUserVO.getMobile());
                            eachDataRow.createCell(6).setCellValue(eachUserVO.getEmail() == null ? "" : eachUserVO.getEmail());
                            if (null != eachUserVO.getCreateUid()) {
                                eachDataRow.createCell(7).setCellValue(eachUserVO.getCreateUid());
                            }
                            if (null != eachUserVO.getCreateTime()) {
                                eachDataRow.createCell(8).setCellValue(DateUtil.formatDate(eachUserVO.getCreateTime(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                            }
                            if (null != eachUserVO.getUpdateUid()) {
                                eachDataRow.createCell(9).setCellValue(eachUserVO.getUpdateUid());
                            }
                            if (null != eachUserVO.getUpdateTime()) {
                                eachDataRow.createCell(10).setCellValue(DateUtil.formatDate(eachUserVO.getUpdateTime(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                            }
                        }
                    }
                }

            }
        });
        return new ResponseResult().ok("导出用户EXCEL成功");
    }
    */

}
